<?php
// 包含数据库连接文件
include '../dbconnect.php';

// 检查所有必要的POST变量是否已设置
if (!isset($_POST['SERVICE_NAME']) || !isset($_POST['SERVICE_TYPE']) || !isset($_POST['SERVICE_CONTENT'])) {
    echo "所有字段都是必填的！";
    exit;
}

// 获取服务信息
$SERVICE_NAME = $_POST['SERVICE_NAME'];
$SERVICE_TYPE = $_POST['SERVICE_TYPE'];
$SERVICE_CONTENT = $_POST['SERVICE_CONTENT'];

// 保存图片
$file = $_FILES['SERVICE_PICTURE']; // 得到传输的数据
$name = $file['name'];
$ext = strtolower(substr($name, strrpos($name, '.') + 1)); // 得到文件类型，并转化为小写
$allow_type = array('jpg', 'jpeg', 'gif', 'png'); // 定义允许上传的类型

// 判断文件类型是否被允许上传
if (!in_array($ext, $allow_type)) {
    echo "不允许的文件类型！";
    exit;
}

// 判断是否是通过HTTP POST上传的
if (!is_uploaded_file($file['tmp_name'])) {
    echo "非法上传！";
    exit;
}

$currentDir = dirname(__FILE__);
// 构建上传路径
$upload_path = $currentDir . '/uploads/'; // 获取当前目录并添加uploads子目录

// 确保uploads目录存在
if (!is_dir($upload_path)) {
    mkdir($upload_path, 0777, true);
}


// 生成唯一的 SERVICE_ID
function generateServiceId($conn) {
    // 获取当前最大的 SERVICE_ID
    $sql = "SELECT SERVICE_ID FROM services ORDER BY SERVICE_ID DESC LIMIT 1";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    $max_id = $row['SERVICE_ID'];

    if ($max_id === null) {
        $next_id = 1;
    } else {
        $last_number = intval(substr($max_id, 9)); // 假设前缀是 "Service_00"
        if ($last_number === 0) {
            $next_id = 1; 
        } else {
            $next_id = $last_number + 1;
        }
    }

    return "Service_" . str_pad($next_id, 3, '0', STR_PAD_LEFT);
}

// 开始移动文件到相应的文件夹
if (move_uploaded_file($file['tmp_name'], $upload_path . $name)) {
    $base_url = 'http://localhost/BWD_Assignment/employee/';
    $SERVICE_PICTURE = $base_url . 'uploads/' . $name;

   
	// 生成唯一的 SERVICE_ID
	$SERVICE_ID = generateServiceId($conn);

    // 将完整的URL路径存储到数据库中
    $sql = "INSERT INTO services (SERVICE_ID, SERVICE_NAME, SERVICE_CONTENT, SERVICE_TYPE, SERVICE_PICTURE) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssss", $SERVICE_ID, $SERVICE_NAME, $SERVICE_CONTENT, $SERVICE_TYPE, $SERVICE_PICTURE);

    if ($stmt->execute()) {
        echo "ADD SUCCESS！";
        header("Location: servicesList.php");
    } else {
        echo "ADD SERVICE FAIL：" . $stmt->error;
    }

    $stmt->close();
    $conn->close();
} else {
    echo "UPLOAD FAIL！";
    exit;
}
?>
